/*
 * Created on 2006-5-11
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.openfans.googlesitemap;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import org.openfans.domain.RootTag;
import org.openfans.persistence.Fetcher;

/**
 * @author yangwu
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class XmlFileCreator {
	private Fetcher fetcher;

	public void setFetcher(Fetcher fetcher) {
		this.fetcher = fetcher;
	}

	/**
	 * @param result
	 *            ,saved the Openfans Object List;
	 * @return the document based on the List ;
	 */
	public Document getDocument(List result) {
		Document doc = DocumentHelper.createDocument();

		Element root = doc.addElement("urlset");
		root
				.addAttribute("xmlns",
						"http://www.google.com/schemas/sitemap/0.84");

		if (result != null) {
			for (Iterator iter = result.iterator(); iter.hasNext();) {
				RootTag tag = (RootTag) iter.next();
				Element url = root.addElement("url");
				Element loc = url.addElement("loc");
				loc.addText("http://www.openfans.net/viewTag.html?id="
						+ tag.getTagId());

				Element lastmod = url.addElement("lastmod");
				if (tag.getLastModifyDate()!= null) {
					lastmod.addText(tag.getLastModifyDate().toString());
				} else {
					lastmod
							.addText(new java.text.SimpleDateFormat(
									"yyyy-MM-dd").format(new Date()));
				}
				Element changefreq = url.addElement("changefreq");
				changefreq.addText("monthly");

				Element priority = url.addElement("priority");
				priority.addText("0.8");
			}
		}
		return doc;
	}

	/**
	 * @param doc
	 * @param fileName
	 *            ,the xml file name which will be creat;
	 */
	public void createXmlFile(Document doc, String fileName) {
		try {
			XMLWriter fw = new XMLWriter(new FileWriter(fileName + ".xml"));
			fw.write(doc);
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("creat xml file failed! ");
			e.printStackTrace();
		}
	}

	/**
	 * 
	 */
	public void execute() {
		// OpenfansService openfans = new OpenfansServiceImpl();
		List result = fetcher.getAllRootTags();
		createXmlFile(getDocument(result), "t_tag_sitemap");
	}

	public static void main(String[] args0) {
		XmlFileCreator creator = new XmlFileCreator();
		creator.execute();
		System.out.println("finish.");
	}
}
